package org.bim.view.drag.design.controller;


import cn.hutool.crypto.SecureUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.base.Splitter;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bim.view.drag.design.api.dto.VisualDbDTO;
import org.bim.view.drag.design.api.req.VisualDbReq;
import org.bim.view.drag.design.api.vo.SqlParamsVO;
import org.bim.view.drag.design.api.vo.TUserVO;
import org.bim.view.drag.design.dao.VisualDbMapper;
import org.bim.view.drag.design.entity.TVisualDb;
import org.bim.view.drag.design.model.HttpResult;
import org.bim.view.drag.design.model.Page;
import org.bim.view.drag.design.util.AssertUtil;
import org.bim.view.drag.design.util.PageUtil;
import org.bim.view.drag.design.util.ThreadLocalUtil;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author pengxg
 * @date 2021/12/16 4:48 下午
 */
@Api
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("db")
public class VisualDbController {
    private static final String AES_KEY = "O2BEeIv399qHQNhD6aGW8R8DEj4bqHXm"; // 和前端保持一致

    private final VisualDbMapper visualDbMapper;

    @GetMapping("detail")
    public HttpResult<TVisualDb> detail(TVisualDb req) {
        return HttpResult.success(visualDbMapper.selectOne(req));
    }

    /**
     * 仅仅自己用的 新增 db的方法
     * @param req 查询参数
     * @return db列表
     */
    @GetMapping("list")
    public HttpResult<Page<TVisualDb>> page(VisualDbReq req) {
        TUserVO userVO = ThreadLocalUtil.getCurrentUser();
        Page<TVisualDb> page = PageUtil.doPage(req.toCondition(), () -> {
            Example example = new Example(TVisualDb.class, false);
            Example.Criteria criteria = example.createCriteria();
            if(!StringUtils.isEmpty(req.getProjectId())){
                criteria.andEqualTo("projectId", req.getProjectId());
            }else {
                criteria .andEqualTo("ownerId", userVO.getId())
                        .andIsNull("projectId");
            }
            return visualDbMapper.selectByExample(example);
        });
        return HttpResult.success(page);
    }

    @PostMapping("save")
    public HttpResult<String> save(@RequestBody TVisualDb form) {
        TUserVO userVO = ThreadLocalUtil.getCurrentUser();
        form.setOwnerId(userVO.getId());
        visualDbMapper.insertSelective(form);
        return HttpResult.success(form.getId());
    }

    @PostMapping("update")
    public HttpResult<String> update(@RequestBody TVisualDb form) {
        visualDbMapper.updateByPrimaryKeySelective(form);
        return HttpResult.success(form.getId());
    }

    @PostMapping("submit")
    public HttpResult submit(@RequestBody TVisualDb form) {
        return Objects.nonNull(form.getId()) ? update(form) : save(form);
    }

    @Transactional
    @PostMapping("remove")
    public HttpResult remove(@RequestParam String ids) {
        Splitter.on(",").split(ids).forEach(id -> {
            TVisualDb entity = visualDbMapper.selectByPrimaryKey(id);
            AssertUtil.isTrue(Objects.nonNull(entity), "对象不存在");
            entity.setIsDeleted(true);
            visualDbMapper.updateByPrimaryKeySelective(entity);
        });
        return HttpResult.success();
    }

    @PostMapping("db-test")
    public HttpResult<Boolean> dbTest(@RequestBody String encryptData) {
        JSONObject jsonObject = decrypt(encryptData);
        TVisualDb db = JSONObject.parseObject(jsonObject.toJSONString(), TVisualDb.class);

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(db.getUrl());
        dataSource.setUsername(db.getUsername());
        dataSource.setPassword(db.getPassword());
        dataSource.setDriverClassName(db.getDriverClass());
        dataSource.setConnectionErrorRetryAttempts(3);
        dataSource.setBreakAfterAcquireFailure(true);
        dataSource.setMaxWait(5000);
        DruidPooledConnection connection=null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException throwables) {
            log.error("获取连接失败,url:{}...",db.getUrl(),throwables);
            return HttpResult.fail(5003,"数据库连接失败");
        }
        if(connection==null){
            return HttpResult.fail(5003,"数据库连接无法建立");
        }else {
            return HttpResult.success(true);
        }
    }

    @GetMapping("db-list")
    public HttpResult<List<VisualDbDTO>> dbList(@RequestParam(required = false) String ownerId, @RequestParam(required = false) String projectId) {
        TUserVO userVO = ThreadLocalUtil.getCurrentUser();
        if (StringUtils.isEmpty(ownerId) || StringUtils.isEmpty(projectId)) {
            ownerId = userVO.getId();
        }
        Example example = new Example(TVisualDb.class, false);
        example.createCriteria()
                .andEqualTo("projectId", projectId)
                .andEqualTo("ownerId", ownerId);
        List<VisualDbDTO> list = visualDbMapper.selectByExample(example).stream()
                .map(db -> new VisualDbDTO(db.getId(), db.getName(), db.getDriverClass()))
                .collect(Collectors.toList());
        return HttpResult.success(list);
    }

    @PostMapping("dynamic-query")
    public HttpResult<Object> dynamicQuery(@RequestBody String encryptData) {
        JSONObject jsonObject = decrypt(encryptData);
        String id = jsonObject.getString("id");
        String sql = jsonObject.getString("sql");
        List<SqlParamsVO> configParams = jsonObject.getObject("params",new TypeReference<List<SqlParamsVO>>(){});
        Map<String,Object> params= new HashMap<>();
        for (SqlParamsVO configParam : configParams) {
            Object realValue = configParam.getParamValue();
            params.put(configParam.getParamKey(),realValue==null?configParam.getParamDefaultValue(): realValue);
        }
        if (StringUtils.isEmpty(id) || StringUtils.isEmpty(sql)) {
            return HttpResult.success();
        }
        TVisualDb db = visualDbMapper.selectByPrimaryKey(id);
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(db.getUrl());
        datasource.setUsername(db.getUsername());
        datasource.setPassword(db.getPassword());
        datasource.setDriverClassName(db.getDriverClass());
        datasource.setConnectionErrorRetryAttempts(3);
        datasource.setBreakAfterAcquireFailure(true);
        datasource.setMaxWait(5000);
        if(!params.isEmpty()){
            NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(datasource);
            try {
                List<Map<String, Object>> data = jdbcTemplate.queryForList(sql,params);
                return HttpResult.success(data);
            } catch (DataAccessException e) {
                String msg = e.getMessage();
                log.error("数据访问失败，{}",msg);
                return HttpResult.fail("数据访问异常, msg: " + msg);
            }
        }else {
            JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
            try {
                List<Map<String, Object>> data = jdbcTemplate.queryForList(sql);
                return HttpResult.success(data);
            } catch (DataAccessException e) {
                String msg = e.getMessage();
                log.error("数据访问失败，{}",msg);
                return HttpResult.fail("数据访问异常, msg: " + msg);
            }
        }



    }

    private JSONObject decrypt(String encryptData) {
        byte[] data = SecureUtil.aes(AES_KEY.getBytes(StandardCharsets.UTF_8)).decrypt(encryptData);
        return JSONObject.parseObject(new String(data));
    }
}
